package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.QualityPlanToDo;
import cc.comac.mom.bean.QualityQarCheckInvoice;
import cc.comac.mom.bean.QualityQarTaskQuery;
import cc.comac.mom.bean.base.LimitPageBean;
import cc.comac.mom.dao.entity.QualityFrrFormEntityDao;
import cc.comac.mom.dao.entity.QualityQarBasicStandardDao;
import cc.comac.mom.dao.entity.QualityQarCheckInvoiceDao;
import cc.comac.mom.dao.entity.QualityQarTaskQueryDao;
import cc.comac.mom.dao.entity.QualityQarVerifyPlanDao;
import cc.comac.mom.entity.QualityFrrFormEntity;
import cc.comac.mom.entity.QualityQarBasicStandardEntity;
import cc.comac.mom.entity.QualityQarCheckInvoiceEntity;
import cc.comac.mom.entity.QualityQarTaskQueryEntity;
import cc.comac.mom.entity.QualityQarVerifyPlanEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;

@Component
@Transactional
public class QualityQarTaskQueryDataHandler extends ServiceImpl<QualityQarTaskQueryDao, QualityQarTaskQueryEntity> {

	@Autowired
	private QualityQarTaskQueryDao qualityQarTaskQueryDao;

	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Autowired
	private QualityQarCheckInvoiceDataHandler qualityQarCheckInvoiceDataHandler;

	@Autowired
	private QualityQarCheckInvoiceDao qualityQarCheckInvoiceDao;

	@Autowired
	private QualityQarBasicStandardDao qualityQarBasicStandardDao;

	@Autowired
	private QualityQarVerifyPlanDataHandler qualityQarVerifyPlanDataHandler;

	@Autowired
	private QualityQarVerifyPlanDao qualityQarVerifyPlanDao;

	@Autowired
	private QualityFrrFormEntityDao qualityFrrFormEntityDao;

	@Autowired
	private QualityParamDataHandler qualityParamDataHandler;

	@Autowired
	private UniversalNumberGenerationDataHandler universalNumberGenerationDataHandler;

	@Autowired
	private QualityPlanToDoDataHandler qualityPlanToDoDataHandler;
	
	/**
	 * 新增qar任务查询数据
	 **/
	public ResultBean insertQarTaskQuery(QualityQarTaskQuery qualityQarTaskQuery) {
		ResultBean resultBean = new ResultBean(true);
		QualityQarTaskQueryEntity innerData = qualityQarTaskQuery.getInnerData();
		if (innerData == null) {
			throw new RuntimeException("无法获取新增qar查询数据！");
		}
		if (StringUtils.isEmpty(innerData.getQarNo())) {
			throw new RuntimeException("新增qar查询中，qar编号不可为空！");
		}
		if (StringUtils.isEmpty(innerData.getPartNo())) {
			throw new RuntimeException("当前件号/图号不可为空！");
		}
		QueryWrapper<QualityQarTaskQueryEntity> queryWrapper = new QueryWrapper<QualityQarTaskQueryEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("qar_purchase_order_number", innerData.getQarNo());
		QualityQarTaskQueryEntity selectOne = qualityQarTaskQueryDao.selectOne(queryWrapper);
		if (selectOne != null) {
			throw new RuntimeException("qar编号" + innerData.getQarNo() + "已存在！");
		}
		baseEntityDataUtil.setBaseEntityData(innerData);
		qualityQarTaskQueryDao.insert(innerData);
		return resultBean;
	}

	/**
	 * 批量新增qar任务查询数据
	 **/
	public ResultBean batchInsertQarTaskQuery(List<QualityQarTaskQuery> list) {
		ResultBean resultBean = new ResultBean();
		ArrayList<QualityQarTaskQueryEntity> entityList = new ArrayList<QualityQarTaskQueryEntity>();
		for (QualityQarTaskQuery qualityQarTaskQuery : list) {
			QualityQarTaskQueryEntity innerData = qualityQarTaskQuery.getInnerData();
			if (innerData == null) {
				throw new RuntimeException("无法获取新增qar查询数据！");
			}
//			
//			  if (StringUtils.isEmpty(innerData.getQarNo())) { throw new
//			  RuntimeException("新增qar查询中，qar编号不可为空！"); }
//			 
			if (StringUtils.isEmpty(innerData.getPartNo())) {
				throw new RuntimeException("当前件号/图号不可为空！");
			}
			QueryWrapper<QualityQarTaskQueryEntity> queryWrapper = new QueryWrapper<QualityQarTaskQueryEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("qar_no", innerData.getQarNo());
			QualityQarTaskQueryEntity selectOne = qualityQarTaskQueryDao.selectOne(queryWrapper);
			if (selectOne != null) {
				throw new RuntimeException("qar编号" + innerData.getQarNo() + "已存在！");
			}
//			baseEntityDataUtil.setBaseEntityData(innerData);
			entityList.add(innerData);
		}
		if (entityList.size() > 0) {
			saveBatch(entityList, entityList.size());
		}
		return resultBean;
	}

	/**
	 * 通过qar任务查询表主键逻辑删除对应表数据
	 **/
	public ResultBean deleteByQarTaskQueryId(long QarTaskQueryId) {
		ResultBean resultBean = new ResultBean(true);
		QualityQarTaskQueryEntity selectById = qualityQarTaskQueryDao.selectById(QarTaskQueryId);
		selectById.setId(QarTaskQueryId);
		selectById.setRowStatus(0);
		baseEntityDataUtil.updateBaseEntityData(selectById);
		qualityQarTaskQueryDao.updateById(selectById);
		return resultBean;
	}

	/**
	 * 更新bar任务查询表对应表数据
	 **/

	public ResultBean updateByQarTaskQueryId(QualityQarTaskQuery qualityQarTaskQuery) {
		ResultBean resultBean = new ResultBean();
		QualityQarTaskQueryEntity innerData = qualityQarTaskQuery.getInnerData();
		if (StringUtils.isEmpty(innerData.getQarNo())) {
			throw new RuntimeException("编辑qar编号为不可空！");
		}
		if (innerData.getId() == 0) {
			throw new RuntimeException("编辑时无法获取qar任务查询主键");
		}
		qualityQarTaskQueryDao.updateById(innerData);
		return resultBean;
	}

	// 按条件查询qar代办对应数据
	public ResultBean selectByFields(QualityQarTaskQuery qualityQarTaskQuery) {
		ResultBean resultBean = new ResultBean(true);
		QualityQarTaskQueryEntity innerData = qualityQarTaskQuery.getInnerData();
		if (qualityQarTaskQuery.getPageNum() == 0) {
			qualityQarTaskQuery.setPageNum(1);
		}
		if (qualityQarTaskQuery.getPageSize() == 0) {
			qualityQarTaskQuery.setPageSize(10);
		}
		Page<QualityQarTaskQueryEntity> page = new Page<QualityQarTaskQueryEntity>(qualityQarTaskQuery.getPageNum(),
				qualityQarTaskQuery.getPageSize(), true);
		QueryWrapper<QualityQarTaskQueryEntity> queryWrapper = new QueryWrapper<QualityQarTaskQueryEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.orderByDesc("creation_time");
		if (StringUtils.isNotEmpty(innerData.getTaskStatus())) {
			queryWrapper.eq("task_status", innerData.getTaskStatus());
		}
		if (StringUtils.isNotEmpty(innerData.getPartNo())) {
			queryWrapper.like("part_no", innerData.getPartNo());
		}
		if (StringUtils.isNotEmpty(innerData.getPartName())) {
			queryWrapper.eq("part_name", innerData.getPartName());
		}
		if (StringUtils.isNotEmpty(innerData.getQarNo())) {
			queryWrapper.eq("qar_no", innerData.getQarNo());
		}
		if (StringUtils.isNotEmpty(innerData.getProductType())) {
			queryWrapper.eq("product_type", innerData.getProductType());
		}
		if (StringUtils.isNotEmpty(innerData.getMaterialType())) {
			queryWrapper.eq("material_type", innerData.getMaterialType());
		}
		if (StringUtils.isNotEmpty(innerData.getTaskExecutor())) {
			queryWrapper.eq("task_executor", baseEntityDataUtil.getCurrentUser());
		}
		if (StringUtils.isNotEmpty(innerData.getExecutorJobNumber())) {
			queryWrapper.eq("executor_job_number", baseEntityDataUtil.getJobNumber());
		}
		IPage<QualityQarTaskQueryEntity> selectPage = null;
		if (StringUtils.isEmpty(innerData.getQarStatus())) {
			// 分页查询任务查询表中的数据
			selectPage = qualityQarTaskQueryDao.selectPage(page, queryWrapper);
			ArrayList<String> list = new ArrayList<String>();
			for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectPage.getRecords()) {
				if (org.apache.commons.lang3.StringUtils.isNoneEmpty(qualityQarTaskQueryEntity.getQarNo())) {
					list.add(qualityQarTaskQueryEntity.getQarNo());
				}
			}
			if (list.size() > 0) {
				// 通过qar编号查询对应检验单数据
				QueryWrapper<QualityQarCheckInvoiceEntity> queryWrapper2 = new QueryWrapper<QualityQarCheckInvoiceEntity>();
				queryWrapper2.in("qar_no", list);
				List<QualityQarCheckInvoiceEntity> selectList = qualityQarCheckInvoiceDao.selectList(queryWrapper2);
				for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectPage.getRecords()) {
					for (QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity : selectList) {
						if (qualityQarTaskQueryEntity.getQarNo().equals(qualityQarCheckInvoiceEntity.getQarNo())) {
							qualityQarTaskQueryEntity.setQarStatus(qualityQarCheckInvoiceEntity.getCurrentStatus());
							qualityQarTaskQueryEntity.setIsFrozen(qualityQarCheckInvoiceEntity.getIsFrozen());
							break;
						}
					}
				}
			}
		} else {
			// 查询所有的qar匹配状态的数据
			QueryWrapper<QualityQarCheckInvoiceEntity> queryWrapper2 = new QueryWrapper<QualityQarCheckInvoiceEntity>();
			queryWrapper2.eq("row_status", 1);
			queryWrapper2.eq("current_status", innerData.getQarStatus());
			List<QualityQarCheckInvoiceEntity> selectList = qualityQarCheckInvoiceDao.selectList(queryWrapper2);
			// 获取qar对应的编号集合
			List<String> list = new ArrayList<String>();
			for (QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity : selectList) {
				if (StringUtils.isNotEmpty(qualityQarCheckInvoiceEntity.getQarNo())) {
					list.add(qualityQarCheckInvoiceEntity.getQarNo());
				}
			}
			// 通过qar编号集合分页查询对应的数据
			queryWrapper.in("qar_no", list);
			selectPage = qualityQarTaskQueryDao.selectPage(page, queryWrapper);
			// 将qar检验表单状态数据插入到qar查询中
			for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectPage.getRecords()) {
				for (QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity : selectList) {
					if (qualityQarTaskQueryEntity.getQarNo().equals(qualityQarCheckInvoiceEntity.getQarNo())) {
						qualityQarTaskQueryEntity.setQarStatus(qualityQarCheckInvoiceEntity.getCurrentStatus());
						qualityQarTaskQueryEntity.setIsFrozen(qualityQarCheckInvoiceEntity.getIsFrozen());
						break;
					}
				}
			}
		}

		@SuppressWarnings("unchecked")
		LimitPageBean<QualityQarTaskQueryEntity> of = (LimitPageBean<QualityQarTaskQueryEntity>) LimitPageBean
				.of(selectPage);
		resultBean.setObject(of);
		return resultBean;
	}

	// 按条件查询qar代办对应数据
	public ResultBean selectMyselfByFields(QualityQarTaskQuery qualityQarTaskQuery) {
		ResultBean resultBean = new ResultBean(true);
		QualityQarTaskQueryEntity innerData = qualityQarTaskQuery.getInnerData();
		if (qualityQarTaskQuery.getPageNum() == 0) {
			qualityQarTaskQuery.setPageNum(1);
		}
		if (qualityQarTaskQuery.getPageSize() == 0) {
			qualityQarTaskQuery.setPageSize(10);
		}
		Page<QualityQarTaskQueryEntity> page = new Page<QualityQarTaskQueryEntity>(qualityQarTaskQuery.getPageNum(),
				qualityQarTaskQuery.getPageSize(), true);
		QueryWrapper<QualityQarTaskQueryEntity> queryWrapper = new QueryWrapper<QualityQarTaskQueryEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.orderByDesc("creation_time");
		if (StringUtils.isNotEmpty(qualityQarTaskQuery.getStatus()) && qualityQarTaskQuery.getStatus().equals("待办")) {
			ArrayList<String> arrayList = new ArrayList<String>();
			arrayList.add("1");
			arrayList.add("2");
			arrayList.add("3");
			arrayList.add("4");
			arrayList.add("5");
			queryWrapper.in("task_status", arrayList);
		}
		if (StringUtils.isNotEmpty(qualityQarTaskQuery.getStatus()) && qualityQarTaskQuery.getStatus().equals("已办")) {
			ArrayList<String> arrayList = new ArrayList<String>();
			arrayList.add("6");
			queryWrapper.in("task_status", arrayList);
		}
		if (StringUtils.isNotEmpty(innerData.getTaskStatus())) {
			queryWrapper.eq("task_status", innerData.getTaskStatus());
		}
		if (StringUtils.isNotEmpty(innerData.getPartNo())) {
			queryWrapper.like("part_no", innerData.getPartNo());
		}
		if (StringUtils.isNotEmpty(innerData.getPartName())) {
			queryWrapper.eq("part_name", innerData.getPartName());
		}
		if (StringUtils.isNotEmpty(innerData.getQarNo())) {
			queryWrapper.eq("qar_no", innerData.getQarNo());
		}
		if (StringUtils.isNotEmpty(innerData.getProductType())) {
			queryWrapper.eq("product_type", innerData.getProductType());
		}
		if (StringUtils.isNotEmpty(innerData.getMaterialType())) {
			queryWrapper.eq("material_type", innerData.getMaterialType());
		}
		queryWrapper.eq("task_executor", baseEntityDataUtil.getCurrentUser());
		if (StringUtils.isNotEmpty(innerData.getExecutorJobNumber())) {
			queryWrapper.eq("executor_job_number", null);
		}
		IPage<QualityQarTaskQueryEntity> selectPage = null;
		if (StringUtils.isEmpty(innerData.getQarStatus())) {
			// 分页查询任务查询表中的数据
			selectPage = qualityQarTaskQueryDao.selectPage(page, queryWrapper);
			ArrayList<String> list = new ArrayList<String>();
			for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectPage.getRecords()) {
				list.add(qualityQarTaskQueryEntity.getQarNo());
			}
			// 通过qar编号查询对应检验单数据
			QueryWrapper<QualityQarCheckInvoiceEntity> queryWrapper2 = new QueryWrapper<QualityQarCheckInvoiceEntity>();
			queryWrapper2.eq("qar_no", list);
			List<QualityQarCheckInvoiceEntity> selectList = qualityQarCheckInvoiceDao.selectList(queryWrapper2);
			for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectPage.getRecords()) {
				for (QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity : selectList) {
					if (qualityQarTaskQueryEntity.getQarNo().equals(qualityQarCheckInvoiceEntity.getQarNo())) {
						qualityQarTaskQueryEntity.setQarStatus(qualityQarCheckInvoiceEntity.getCurrentStatus());
						break;
					}
				}
			}
		} else {
			// 查询所有的qar匹配状态的数据
			QueryWrapper<QualityQarCheckInvoiceEntity> queryWrapper2 = new QueryWrapper<QualityQarCheckInvoiceEntity>();
			queryWrapper2.eq("row_status", 1);
			queryWrapper2.eq("current_status", innerData.getQarStatus());
			List<QualityQarCheckInvoiceEntity> selectList = qualityQarCheckInvoiceDao.selectList(queryWrapper2);
			// 获取qar对应的编号集合
			List<String> list = new ArrayList<String>();
			for (QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity : selectList) {
				list.add(qualityQarCheckInvoiceEntity.getQarNo());
			}
			// 通过qar编号集合分页查询对应的数据
			queryWrapper.in("qar_no", list);
			selectPage = qualityQarTaskQueryDao.selectPage(page, queryWrapper);
			// 将qar检验表单状态数据插入到qar查询中
			for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectPage.getRecords()) {
				for (QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity : selectList) {
					if (qualityQarTaskQueryEntity.getQarNo().equals(qualityQarCheckInvoiceEntity.getQarNo())) {
						qualityQarTaskQueryEntity.setQarStatus(qualityQarCheckInvoiceEntity.getCurrentStatus());
						break;
					}
				}
			}
		}

		@SuppressWarnings("unchecked")
		LimitPageBean<QualityQarTaskQueryEntity> of = (LimitPageBean<QualityQarTaskQueryEntity>) LimitPageBean
				.of(selectPage);
		resultBean.setObject(of);
		return resultBean;
	}

	// 当手动生成qar任务时，进行任务合拼
	public ResultBean qarTaskMerge(List<QualityQarTaskQuery> list1) {
		ResultBean resultBean = new ResultBean(true);

		List<Long> entityList = new ArrayList<Long>();
		for (QualityQarTaskQuery qualityQarTaskQuery : list1) {
			entityList.add(qualityQarTaskQuery.getInnerData().getId());
		}
		QueryWrapper<QualityQarTaskQueryEntity> queryWrapper2 = new QueryWrapper<QualityQarTaskQueryEntity>();
		queryWrapper2.eq("row_status", 1);
		queryWrapper2.in("qar_task_query_id", entityList);
		List<QualityQarTaskQueryEntity> list = qualityQarTaskQueryDao.selectList(queryWrapper2);
		validateTaskGenerate(list);
		if (list.size() > 0) {
			// 批次数据的拼接
			String serialNumber = "";
			double quantity = 0;
			for (QualityQarTaskQueryEntity qualityQarTaskQuery : list) {
				String[] split = serialNumber.split(",");
				if ( Arrays.binarySearch(split, qualityQarTaskQuery.getBatchNumber()) <0) {
					if (org.apache.commons.lang3.StringUtils.isEmpty(serialNumber)) {
						serialNumber = qualityQarTaskQuery.getSerialNumber();
					} else {
						serialNumber = serialNumber + "," + qualityQarTaskQuery.getSerialNumber();
					}
				}
				// 数量合并
				quantity = quantity + qualityQarTaskQuery.getQuantity();

				QualityQarBasicStandardEntity selectById = qualityQarBasicStandardDao
						.selectById(qualityQarTaskQuery.getQarBasicStandardId());
				if (!selectById.getStatus().equals("2")) {
					throw new RuntimeException("当前母本 " + selectById.getQarBasicStandardNumber() + " 未启用，无法合拼生成qar");
				}
			}
			// 校验数据是否允许合拼
			for (int i = 0; i < list.size() - 1; i++) {
				QualityQarTaskQueryEntity qualityQarTaskQueryEntity = list.get(i);
				QualityQarTaskQueryEntity qualityQarTaskQueryEntityNext = list.get(i + 1);
				if (!qualityQarTaskQueryEntity.getPurchaseOrder()
						.equals(qualityQarTaskQueryEntityNext.getPurchaseOrder())) {
					throw new RuntimeException("不同的采购订单无法进行合拼！");
				}
				if (!qualityQarTaskQueryEntity.getVendorName().equals(qualityQarTaskQueryEntityNext.getVendorName())) {
					throw new RuntimeException("不同的供应商无法进行合拼！");
				}
				if (!qualityQarTaskQueryEntity.getPartNo().equals(qualityQarTaskQueryEntityNext.getPartNo())) {
					throw new RuntimeException("不同的零件无法进行合拼！");
				}
				if (!qualityQarTaskQueryEntity.getMaterial().equals(qualityQarTaskQueryEntityNext.getMaterial())) {
					throw new RuntimeException("不同的物料名无法进行合拼！");
				}
				// 通过主键查询对应的查询数据，然后删除数据，重建新的合拼后的数据
				List<Long> ids = new ArrayList<Long>();
				for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity1 : list) {
					long id = qualityQarTaskQueryEntity1.getId();
					ids.add(id);
				}
				QualityQarTaskQueryEntity innerData = list.get(0);
				baseEntityDataUtil.setBaseEntityData(innerData);
				// 新增一条qar数据
				List<QualityQarCheckInvoice> checkInvoiceList = new ArrayList<QualityQarCheckInvoice>();
				QualityQarCheckInvoice qualityQarCheckInvoice = new QualityQarCheckInvoice();
				QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity = new QualityQarCheckInvoiceEntity();
				qualityQarCheckInvoice.setInnerData(qualityQarCheckInvoiceEntity);
				qualityQarCheckInvoiceEntity.setPurchaseOrder(innerData.getPurchaseOrder());
				qualityQarCheckInvoiceEntity.setShipNo(innerData.getShipNo());
				qualityQarCheckInvoiceEntity.setQuantity(new BigDecimal(quantity));
				qualityQarCheckInvoiceEntity.setProductType(innerData.getProductType());
				qualityQarCheckInvoiceEntity.setMaterialType(innerData.getMaterialType());
				qualityQarCheckInvoiceEntity.setUom(innerData.getUom());
				qualityQarCheckInvoiceEntity.setVendor(innerData.getVendorName());
				qualityQarCheckInvoiceEntity.setPartType(innerData.getMaterialType());
				qualityQarCheckInvoiceEntity.setMaterialNumber(innerData.getMaterial());
				qualityQarCheckInvoiceEntity.setPartNo(innerData.getPartNo());
				qualityQarCheckInvoiceEntity.setPartName(innerData.getPartName());
				qualityQarCheckInvoiceEntity.setStoveNo(innerData.getVendorBatchNumber());// 炉批号就是供应商批次号
				qualityQarCheckInvoiceEntity.setQarTaskId(innerData.getId());
				qualityQarCheckInvoiceEntity.setQualityPurchaseOrderInfoId(innerData.getQualityPurchaseOrderInfoId());
				qualityQarCheckInvoiceEntity.setSerialNumber(innerData.getSerialNumber());
				boolean validateQarFrrForm = validateQarFrrForm(innerData);
				if (validateQarFrrForm) {
					// 为让步信息
					qualityQarCheckInvoiceEntity.setIsFrr("1");
				} else {
					qualityQarCheckInvoiceEntity.setIsFrr("0");
				}
				boolean validateQarVerifyPlan = validateQarVerifyPlan(innerData);
				if (validateQarVerifyPlan) {
					// 是否为纠正措施
					qualityQarCheckInvoiceEntity.setIsVerify("1");
				} else {
					qualityQarCheckInvoiceEntity.setIsVerify("0");
				}

				checkInvoiceList.add(qualityQarCheckInvoice);
				// 新增检验单数据
				ResultBean manualCreateQar = qualityQarCheckInvoiceDataHandler.manualCreateQar(checkInvoiceList);
				if (!manualCreateQar.success) {
					throw new RuntimeException(manualCreateQar.getMessage());
				}
				for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity2 : list) {
					qualityQarTaskQueryEntity2.setRowStatus(0);
					baseEntityDataUtil.updateBaseEntityData(qualityQarTaskQueryEntity2);
				}
				// 逻辑删除查询表数据
				updateBatchById(list, list.size());
				// 设置qarNo和任务状态
				innerData.setQarNo(checkInvoiceList.get(0).getInnerData().getQarNo());
				innerData.setTaskStatus("1");
				// 合拼后新增一条数据到任务查询表中
				if (innerData.getQarBasicStandardId() == 0) {
					innerData.setQarBasicStandardId(qualityQarCheckInvoiceEntity.getQarBasicStandardId());
				}
				innerData.setSerialNumber(serialNumber);
				innerData.setQarNo(qualityQarCheckInvoiceEntity.getQarNo());
				qualityQarTaskQueryDao.insert(innerData);
			}
		}
		return resultBean;
	}

	// 当手动生成qar任务时，进行任务单个的生成,生成多个qar
	public ResultBean qarTaskSingleInsert(List<QualityQarTaskQuery> list) {
		ResultBean resultBean = new ResultBean(true);

		if (list == null || list.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		ArrayList<QualityQarCheckInvoice> listQualityQarCheckInvoice = new ArrayList<QualityQarCheckInvoice>();
		ArrayList<Long> ids = new ArrayList<Long>();
		for (QualityQarTaskQuery item : list) {
			QualityQarTaskQueryEntity innerData = item.getInnerData();
			if (innerData == null) {
				throw new RuntimeException("数据为空");
			}
			ids.add(innerData.getId());
		}
		List<QualityQarTaskQueryEntity> selectBatchIds = qualityQarTaskQueryDao.selectBatchIds(ids);
		validateTaskGenerate(selectBatchIds);
		for (QualityQarTaskQueryEntity item : selectBatchIds) {

			QualityQarBasicStandardEntity selectById = qualityQarBasicStandardDao
					.selectById(item.getQarBasicStandardId());
			if (!selectById.getStatus().equals("2")) {
				throw new RuntimeException("当前母本" + selectById.getQarBasicStandardNumber() + "未启用，无法生成qar！");
			}
			QualityQarCheckInvoice qualityQarCheckInvoice = new QualityQarCheckInvoice();
			QualityQarCheckInvoiceEntity qualityQarCheckInvoiceEntity = new QualityQarCheckInvoiceEntity();
			qualityQarCheckInvoiceEntity.setPurchaseOrder(item.getPurchaseOrder());
			qualityQarCheckInvoiceEntity.setQuantity(new BigDecimal(item.getQuantity()));
			qualityQarCheckInvoiceEntity.setUom(item.getUom());
			qualityQarCheckInvoiceEntity.setVendor(item.getVendorName());
			qualityQarCheckInvoiceEntity.setPartType(item.getMaterialType());
			qualityQarCheckInvoiceEntity.setMaterialNumber(item.getMaterial());
			qualityQarCheckInvoiceEntity.setPartNo(item.getPartNo());
			qualityQarCheckInvoiceEntity.setPartName(item.getPartName());
			qualityQarCheckInvoiceEntity.setStoveNo(item.getVendorBatchNumber());// 炉批号就是供应商批次号
			qualityQarCheckInvoiceEntity.setStatus("0");
			qualityQarCheckInvoiceEntity.setQualityPurchaseOrderInfoId(item.getQualityPurchaseOrderInfoId());
			qualityQarCheckInvoiceEntity.setSerialNumber(item.getSerialNumber());
			qualityQarCheckInvoice.setInnerData(qualityQarCheckInvoiceEntity);
			qualityQarCheckInvoiceEntity.setQarTaskId(item.getId());
			// 并校验对应让步信息和纠正信息
			boolean validateQarFrrForm = validateQarFrrForm(item);
			if (validateQarFrrForm) {
				// 是让步信息
				qualityQarCheckInvoice.getInnerData().setIsFrr("1");
			} else {
				qualityQarCheckInvoice.getInnerData().setIsFrr("0");
			}
			boolean validateQarVerifyPlan = validateQarVerifyPlan(item);
			if (validateQarVerifyPlan) {
				// 是纠正措施
				qualityQarCheckInvoice.getInnerData().setIsVerify("1");
			} else {
				qualityQarCheckInvoice.getInnerData().setIsVerify("0");
			}
			listQualityQarCheckInvoice.add(qualityQarCheckInvoice);
		}
		ResultBean resultBean2 = qualityQarCheckInvoiceDataHandler.manualCreateQar(listQualityQarCheckInvoice);
		if (!resultBean2.success) {
			throw new RuntimeException(resultBean2.getMessage());
		}
		for (QualityQarTaskQueryEntity qualityQarTaskQueryEntity : selectBatchIds) {
			for (QualityQarCheckInvoice qualityQarCheckInvoice : listQualityQarCheckInvoice) {
				if (qualityQarTaskQueryEntity.getId() == qualityQarCheckInvoice.getInnerData().getQarTaskId()) {
					qualityQarTaskQueryEntity.setQarNo(qualityQarCheckInvoice.getInnerData().getQarNo());
					qualityQarTaskQueryEntity.setQarBasicStandardId(qualityQarCheckInvoice.getInnerData().getQarBasicStandardId());
					qualityQarTaskQueryEntity.setTaskStatus("1");
				}
			}
		}
		// 更新插入qarNo和改变任务查询状态对应数据
		updateBatchById(selectBatchIds, selectBatchIds.size());
		return resultBean;
	}

	/**
	 * 2.校验纠正措施计划中是否存在匹配数据，存在一次份数扣减1并且更改是否纠正字段为是
	 **/
	public boolean validateQarVerifyPlan(QualityQarTaskQueryEntity qualityQarTaskQuery) {
		// 操作前先判断是否存在纠正措施次数为0的有的话将其逻辑删除

		// 校验纠正措施计划数据 通过零件号查询
		QueryWrapper<QualityQarVerifyPlanEntity> queryWrapper = new QueryWrapper<QualityQarVerifyPlanEntity>();
		queryWrapper.eq("partno", qualityQarTaskQuery.getPartNo());
//		queryWrapper.gt("copy_number", 0);
		queryWrapper.eq("row_status", 1);
		List<QualityQarVerifyPlanEntity> list = qualityQarVerifyPlanDao.selectList(queryWrapper);
		if (list != null && list.size() > 0) {
			list.forEach(item -> {
				if (item.getCopyNumber() == 0) {
					item.setRowStatus(0);
				} else if (item.getCopyNumber() > 0) {
					item.setCopyNumber(item.getCopyNumber() - 1);
				}
				baseEntityDataUtil.updateBaseEntityData(item);
			});
			int flag = 0;
			for (QualityQarVerifyPlanEntity qualityQarVerifyPlanEntity : list) {
				if (qualityQarVerifyPlanEntity.getRowStatus() == 1) {
					flag = 1;
				}
			}
			// 更新份数
			if (list.size() > 0) {
				qualityQarVerifyPlanDataHandler.updateBatchById(list, list.size());
			}
			return flag == 0 ? false : true;
		}
		return false;
	}

	/**
	 * 2.校验让步信息是否匹配对应数据，匹配将更改是否让步字段为是
	 **/

	public boolean validateQarFrrForm(QualityQarTaskQueryEntity qualityQarTaskQuery) {
		// 判断frr是否让步
		QueryWrapper<QualityFrrFormEntity> queryWrapper3 = new QueryWrapper<QualityFrrFormEntity>();
		queryWrapper3.eq("batch", qualityQarTaskQuery.getBatchNumber());
		queryWrapper3.eq("serial_num", qualityQarTaskQuery.getSerialNumber());
		// 未作废的
		queryWrapper3.eq("status", 0);
		List<QualityFrrFormEntity> selectList2 = qualityFrrFormEntityDao.selectList(queryWrapper3);
		if (selectList2.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 1.校验查询对应数据是否存在母本，当不存在时异常提示
	 * 
	 **/
	public void validateTaskGenerate(List<QualityQarTaskQueryEntity> list) {
		for (QualityQarTaskQueryEntity qualityQarTaskQuery : list) {
			QueryWrapper<QualityQarBasicStandardEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("part_number", qualityQarTaskQuery.getPartNo());
			queryWrapper.like("material_number", qualityQarTaskQuery.getMaterial());
			QualityQarBasicStandardEntity qualityQarBasicStandardEntity = qualityQarBasicStandardDao
					.selectOne(queryWrapper);
			if (qualityQarBasicStandardEntity == null) {
				throw new RuntimeException("无法获取对应的母本信息！");
			} else if (qualityQarBasicStandardEntity != null && !qualityQarBasicStandardEntity.getStatus()
					.equals(MomConstants.QUALITY_QAR_BASIC_STANDARD_QIYONG)) {
				throw new RuntimeException(
						"对应母本" + "状态必须为启用才能生成qar");
			} else {
				qualityQarTaskQuery.setQarBasicStandardId(qualityQarBasicStandardEntity.getId());
			}
			
			// 校验同时反冲查看计划代办数据中是否存在对应母本，当存在时删除对应数据
//			List<QualityPlanToDo> unTreatedByPartNoAndToDoStatus = qualityPlanToDoDataHandler.getUnTreatedByPartNoAndToDoStatus(qualityQarTaskQuery.getPartNo(), Arrays.asList(3,2), qualityQarTaskQuery.getMaterial());
//			if (unTreatedByPartNoAndToDoStatus != null && unTreatedByPartNoAndToDoStatus.size() > 0) {
//				qualityPlanToDoDataHandler.logicDeletePlanTodoList(unTreatedByPartNoAndToDoStatus);
//			}
			
		}
	}

}
